package com.example.translation.websocket;

import com.example.translation.entity.TranslationRequest;
import com.example.translation.entity.TranslationResponse;
import com.example.translation.service.TranslationService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.yeauty.annotation.*;
import org.yeauty.pojo.Session;

import java.util.Objects;

@Component
@ServerEndpoint(path = "/translate")
public class TranslationWebSocketServer {

    private static TranslationService translationService;
    private static ObjectMapper objectMapper;
    
    // 由于Spring不支持直接注入到WebSocket组件，使用setter方式注入
    public TranslationWebSocketServer(TranslationService translationService, ObjectMapper objectMapper) {
        TranslationWebSocketServer.translationService = translationService;
        TranslationWebSocketServer.objectMapper = objectMapper;
    }
    
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("WebSocket连接已建立: " + session.id());
    }
    
    @OnClose
    public void onClose(Session session) {
        System.out.println("WebSocket连接已关闭: " + session.id());
    }
    
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            // 解析客户端发送的消息
            TranslationRequest request = objectMapper.readValue(message, TranslationRequest.class);
            
            // 调用翻译服务
            String translatedText = translationService.translate(
                request.getText(), 
                request.getFromLanguage(), 
                request.getToLanguage()
            );
            
            // 构建响应
            TranslationResponse response = new TranslationResponse(
                request.getText(),
                translatedText,
                request.getFromLanguage(),
                request.getToLanguage(),
                true
            );
            
            // 发送翻译结果给客户端
            session.sendText(objectMapper.writeValueAsString(response));
        } catch (Exception e) {
            try {
                TranslationResponse errorResponse = new TranslationResponse();
                errorResponse.setSuccess(false);
                errorResponse.setErrorMessage(e.getMessage());
                session.sendText(objectMapper.writeValueAsString(errorResponse));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.err.println("WebSocket错误: " + throwable.getMessage());
        throwable.printStackTrace();
    }
}
